package com.example.fast.web.aop;

import com.example.fast.common.constant.AppConstant;
import com.example.fast.common.exception.BaseException;
import com.example.fast.common.util.HttpContextUtils;
import com.example.fast.dao.UserDao;
import com.example.fast.domain.entity.UserEntity;
import com.example.fast.common.annotation.UserType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

import static com.example.fast.common.exception.AppExceptionEnum.TOKEN_ERROR;

/**
 * 用户类型判断拦截
 */
@Aspect
@Component
public class UserTypeAspect {

    private final UserDao userDao;

    public UserTypeAspect(UserDao userDao) {
        this.userDao = userDao;
    }

    @Before("@annotation(com.example.fast.common.annotation.UserType)")
    public void doBefore(JoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

        Method method = methodSignature.getMethod();
        UserType annotation = method.getAnnotation(UserType.class);

        //校验用户类型
        Object userId = HttpContextUtils.getHttpServletRequest().getAttribute(AppConstant.USER_KEY);
        UserEntity one = userDao.selectById((Long) userId);
        if (!one.getUserType().equals(annotation.value())) {
            throw new BaseException(TOKEN_ERROR, annotation.desc());
        }
    }
}